/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.stock.service;

import java.util.List;

import com.thinkgem.jeesite.modules.stock.entity.Container;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.stock.entity.Warehouse;
import com.thinkgem.jeesite.modules.stock.dao.WarehouseDao;
import com.thinkgem.jeesite.modules.stock.entity.WarehouseLoc;
import com.thinkgem.jeesite.modules.stock.dao.WarehouseLocDao;

/**
 * 仓库Service
 * @author 仓库
 * @version 2019-12-22
 */
@Service
@Transactional(readOnly = true)
public class WarehouseService extends CrudService<WarehouseDao, Warehouse> {

	@Autowired
	private WarehouseLocDao warehouseLocDao;
	
	public Warehouse get(String id) {
		Warehouse warehouse = super.get(id);
		warehouse.setWarehouseLocList(warehouseLocDao.findList(new WarehouseLoc(warehouse)));
		return warehouse;
	}
	
	public List<Warehouse> findList(Warehouse warehouse) {
		return super.findList(warehouse);
	}
	
	public Page<Warehouse> findPage(Page<Warehouse> page, Warehouse warehouse) {
		return super.findPage(page, warehouse);
	}

	@Autowired
	private ContainerService containerService;

	@Transactional(readOnly = false)
	public void save(Warehouse warehouse) {
		super.save(warehouse);
		for (WarehouseLoc warehouseLoc : warehouse.getWarehouseLocList()){
			if (warehouseLoc.getId() == null){
				continue;
			}
			if (WarehouseLoc.DEL_FLAG_NORMAL.equals(warehouseLoc.getDelFlag())){
				if (StringUtils.isBlank(warehouseLoc.getId())){
					warehouseLoc.setC(warehouse);
					warehouseLoc.preInsert();
					warehouseLocDao.insert(warehouseLoc);
					Container  container=new Container();
					container.setC(warehouseLoc);
					container.setCtype(warehouseLoc.getCtype());
					container.setName(warehouseLoc.getName());
					container.setStatus("1");
					container.setNumber(warehouseLoc.getNumber());
					containerService.save(container);

				}else{
					warehouseLoc.preUpdate();
					warehouseLocDao.update(warehouseLoc);
				}

			}else{
				warehouseLocDao.delete(warehouseLoc);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Warehouse warehouse) {
		super.delete(warehouse);
		warehouseLocDao.delete(new WarehouseLoc(warehouse));
	}
	
}